package com.chuangke.file.schedule;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chuangke.admin.entity.SysDept;
import com.chuangke.admin.entity.SysUser;
import com.chuangke.admin.service.SysDeptService;
import com.chuangke.admin.service.SysUserService;
import com.chuangke.common.constant.FileConstants;
import com.chuangke.common.constant.Masks;
import com.chuangke.file.dao.FileInfoMapper;
import com.chuangke.file.model.FileDbank;
import com.chuangke.file.model.FileInfo;
import com.chuangke.file.model.FileInfoDeleted;
import com.chuangke.file.service.FileDbankService;
import com.chuangke.file.service.FileHandleService;
import com.chuangke.file.service.FileInfoDeletedService;
import com.chuangke.fss.FSSClient;
import com.chuangke.fss.model.FSSObject;

@Configuration
@EnableScheduling
public class FileScheduleTask {

	private static final Logger logger = LoggerFactory.getLogger(FileScheduleTask.class);

	@Autowired
	private FileInfoDeletedService fileInfoDeleteService;
	@Autowired
	private FSSClient fssClient;

	@Autowired
	private FileInfoMapper fileInfoMapper;
	@Autowired
	private FileHandleService fileHandleService;

//	@Scheduled(cron = "0 0 0/1 * * ?") // 0 17 9 * * ?
	private void configureTasks() {
		logger.warn("开始-执行删除已经删除文件定时任务时间: " + LocalDateTime.now());

		int canDelete = fileInfoDeleteService.removeCanDelete();
		logger.warn("有{}个文件存在元数据中，无须在文件系统中删除 ", canDelete);

		List<FileInfoDeleted> deleteFiles = fileInfoDeleteService.listCanDelete();
		if (CollectionUtils.isEmpty(deleteFiles)) {
			logger.warn("执行删除已删除文件0个 ");
			logger.warn("结束-执行删除已经删除文件定时任务时间: " + LocalDateTime.now());
			return;
		}

		deleteFiles.forEach(fileInfo -> {
			FSSObject fssObject = new FSSObject();
			try {
				fssObject.setStorage1(fileInfo.getStorage1());
				fssObject.setStorage2(fileInfo.getStorage2());
				fssClient.getFss(fileInfo.getStorageType()).delete(fssObject);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
			try {
				fssObject.setStorage1(fileInfo.getThumStorage1());
				fssObject.setStorage2(fileInfo.getThumStorage2());
				fssClient.getFss(fileInfo.getStorageType()).delete(fssObject);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		});

//		fileInfoDeleteService.removeByIds(deleteFiles.stream().map(FileInfoDelete::getId).collect(Collectors.toList())) ;
		int deleted = fileInfoDeleteService.removeDeleted();

		logger.warn("删除元数据{}条，文件系统中删除文件{}个 ", deleted, deleteFiles.size());
		logger.warn("结束-执行删除已经删除文件定时任务时间: " + LocalDateTime.now());
	}

//	@Scheduled(cron = "0 0 0/2 * * ?")
	private void handleFile() {
		logger.warn("执行建立文档索引定时任务时间: " + LocalDateTime.now());
		List<FileInfo> list = fileInfoMapper.selectList(new QueryWrapper<FileInfo>().lambda()
				.eq(FileInfo::getType, FileInfo.TYPE_FILE).eq(FileInfo::getIndexStatus, Masks.BOOL_NO));
		logger.warn("执行建立文档索引文件数量: {}", (CollectionUtils.isEmpty(list) ? 0 : list.size()));
		if (CollectionUtils.isEmpty(list)) {
			return;
		}
		list.forEach(file -> {
			FSSObject fssObject = file.convert();
			file.setContent(fssClient.getFss(fssObject.getStorageType()).download(fssObject).getObjectContent());
			fileHandleService.handle(file);
		});
	}
	
	@Autowired
	private SysDeptService sysDeptService ;
	@Autowired
	private SysUserService sysUserService ;
	@Autowired
	private FileDbankService fileDbankService ;
	
//	@Scheduled(cron = "0 0 0/2 * * ?")
	public void registDbank() {
		logger.warn("执行注册网盘开始: " + LocalDateTime.now());
		
		List<FileDbank> dbankList = fileDbankService.listDbank() ;
		Map<String,FileDbank> dbankMap = dbankList.stream().collect(Collectors.toMap(dbank -> dbank.getBelongId() + "-" + dbank.getType(), a -> a));
		
		Map<String,SysDept> deptMap = sysDeptService.findMap() ;
		deptMap.values().forEach(dept->{
			if(Masks.BOOL_YES.equals(dept.getIsLastLevel())) {
				if(!dbankMap.containsKey(dept.getId()+"-"+FileDbank.TYPE_DEPT)) {
					fileDbankService.regist(dept.getId(), FileDbank.TYPE_DEPT, dept.getName()+"的网盘", new BigInteger(FileConstants.DEFAULT_DBANK_SIZE));
				}
			}
		});
		
		Map<String,SysUser>  userMap = sysUserService.findMap() ;
		userMap.values().forEach(user->{
			if(!dbankMap.containsKey(user.getId()+"-"+FileDbank.TYPE_PERSON)) {
				fileDbankService.regist(user.getId(), FileDbank.TYPE_PERSON, user.getNickName()+"的网盘", new BigInteger(FileConstants.DEFAULT_DBANK_SIZE));
			}
		});
		
		logger.warn("执行注册网盘结束: " + LocalDateTime.now());
	}

}